package com.ys.service.business.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.vo.R;
import com.ys.dto.AddDto;
import com.ys.dto.EditDto;
import com.ys.entity.business.TpProductActive;
import com.ys.entity.business.TpProductActiveComponent;
import com.ys.entity.business.TpProductBasis;
import com.ys.entity.business.TpProductBasisComponent;
import com.ys.entity.shiro.LoginUser;
import com.ys.entity.sys.YsCol;
import com.ys.mapper.business.DiySqlMapper;
import com.ys.mapper.business.TpProductActiveComponentMapper;
import com.ys.mapper.business.TpProductBasisComponentMapper;
import com.ys.service.business.TpProductBasicComponentService;
import com.ys.util.CheckUtil;
import com.ys.util.RandomUtil;
import com.ys.util.shiro.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service("tpProductBasicComponentService")
public class TpProductBasicComponentServiceImpl implements TpProductBasicComponentService {
	
	@Autowired
	private TpProductBasisComponentMapper tpProductBasisComponentMapper;
	@Autowired
	private TpProductActiveComponentMapper tpProductActiveComponentMapper;
	@Autowired
	private DiySqlMapper diySqlMapper;
	@Autowired
	private CheckUtil checkUtil;


	@Override
	public R add(String pcode) {
		
		if (pcode == null ) {
			return R.error("商品编码不能为空");
		} else if (new TpProductBasis().setCode(pcode).count() == 0) {
			return R.error("该商品不存在");
		}
		
		// 子件编码
		String code = "";
		TpProductBasisComponent max = new TpProductBasisComponent().setPcode(pcode).setOrderby("A.code desc").queryFirst();
		if (max == null) {
			code = pcode + "-01";
		} else {
			String codeCurrent = max.getCode();
			Integer nextNo = Integer.parseInt(codeCurrent.substring(codeCurrent.indexOf("-") + 1)) + 1;
			String lastCode = nextNo < 10 ? ("0" + nextNo) : nextNo.toString();
			code = pcode + "-" + lastCode;
		}
		
		TpProductBasisComponent entity = null;
		{
			String guid = RandomUtil.getGUID();
			LoginUser loginUser = ShiroUtils.getLoginUser();
			String createUser = loginUser.getUserId();
			Date createTime = new Date();
			String updateUser = null;
			Date updateTime = createTime;
			String name = null;
			BigDecimal num = null;
			String remark = null;
			BigDecimal bPrice = null;
			BigDecimal bPrices = null;
			String linkIn = null;
			String linkInMark = null;
//			entity = TpProductBasisComponent.tpProductBasisComponent(guid, createUser, createTime, updateUser, updateTime, pcode, name, code, num, remark, bPrice, bPrices, linkIn, linkInMark);
		}
		tpProductBasisComponentMapper.insert(entity);
		
		// 返回数据，用于表格加载
		return R.ok(entity);
	}

	/**
	 * 删除
	 * @operateCompanyId operateCompanyId
	 * @return
	 */
	@Override
	@Transactional
	public R deleteTpProductBasic(Map<String, Object> params) {
		String[] strs = params.get("list").toString().split(",");
		for(int i=0,len=strs.length;i<len;i++){

			diySqlMapper.deleteTpProductBasis(Long.valueOf(strs[i]));
		}

		return R.ok(EditDto.closeAndReload());
	
	}



	/**
	 * 新增，同时新增相关listing库子件信息
	 */
	@Override
	public com.ys.vo.R addAndProductActive(Map<String, Object> params) {
		//获取子件编码
		String pcode = params.get("pcode").toString();//母件编码
		//查询最大的一条编号
		List<TpProductBasisComponent> tpProductBasisComponentList = new TpProductBasisComponent().setPcode(pcode).queryList();
		Integer currentNo = 0;
		if (tpProductBasisComponentList.size() != 0){
			currentNo = tpProductBasisComponentList.size();
		}
		currentNo++;
		String currentNoNew = String.format("%02d",currentNo);
		//商品编码-01，-02，-03.....
		String code = pcode+"-"+currentNoNew;
		params.put("code",code);
		// 验证订单号
		if (new TpProductBasisComponent().setCode(code).count() > 0) {
			return com.ys.vo.R.error("子件编码已存在");
		}

		TpProductBasisComponent entity = JSON.parseObject(JSON.toJSONString(params), TpProductBasisComponent.class);
		tpProductBasisComponentMapper.insert(entity);
		//listing库子件同步
		TpProductActiveComponent hasComponent = new TpProductActiveComponent().setCode(code).queryFirst();
		TpProductActiveComponent tpProductActiveComponent = JSON.parseObject(JSON.toJSONString(params), TpProductActiveComponent.class);
		if(hasComponent!=null){//修改
			diySqlMapper.updateProductActiveComponent(tpProductActiveComponent);
		}else {//新增
			tpProductActiveComponent.setCode(entity.getCode());
			tpProductActiveComponentMapper.insert(tpProductActiveComponent);
		}
		return com.ys.vo.R.ok(AddDto.closeAndReload());
	}


	/**
	 * 修改，同时修改相关listing子件信息
	 */
	@Override
	public com.ys.vo.R editAndProductActive(Map<String, Object> params) {
		TpProductBasisComponent entity = JSON.parseObject(JSON.toJSONString(params), TpProductBasisComponent.class);
		tpProductBasisComponentMapper.update(entity);
		//listing库子件保存
		TpProductActiveComponent hasComponent = new TpProductActiveComponent().setCode(entity.getCode()).queryFirst();
		TpProductActiveComponent tpProductActiveComponent = JSON.parseObject(JSON.toJSONString(params), TpProductActiveComponent.class);
		if(hasComponent!=null){//修改
			diySqlMapper.updateProductActiveComponent(tpProductActiveComponent);
		}else {//新增
			tpProductActiveComponent.setCode(entity.getCode());
			tpProductActiveComponentMapper.insert(tpProductActiveComponent);
		}
		return com.ys.vo.R.ok(AddDto.closeAndReload());
	}

	/**
	 * 保存，同时修改相关商品库子件信息
	 */
	@Override
	public synchronized com.ys.vo.R saveAndProductActive(List<Map<String, Object>> paramsNewByComponent, Long pid, String editType) {
		String errorMsg = null;
		//遍历子件数据
		for (Map<String, Object> item:paramsNewByComponent) {
			boolean isAdd = true;
			if(item.get("id")!=null){
				Long id = Long.parseLong(item.get("id").toString());
				TpProductBasisComponent tpProductBasisComponent = new TpProductBasisComponent().setId(id).queryFirst();
				if(tpProductBasisComponent!=null){
					isAdd = false;
				}
			}
			com.ys.vo.R returnMsg = new com.ys.vo.R();
			//新增或修改
			if(isAdd){//新增
				returnMsg = addAndProductActive(item);

			}else {//修改
				returnMsg = editAndProductActive(item);
			}
			if(returnMsg.getCode()==1){//失败
				errorMsg = returnMsg.getMsg();
			}
		}
		if(errorMsg!=null){
			return com.ys.vo.R.error(errorMsg);
		}else {
			return com.ys.vo.R.ok(AddDto.gotoEdit("/web/business/tpProductActive/toEdit?id=" + pid+"&editType="+editType));
		}
	}



	/**
	 * 删除，同时删除相关listing库子件信息
	 */
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public com.ys.vo.R delAndProductActive(List<String> idList, String code) {
		TpProductBasis tpProductBasis = new TpProductBasis().setCode(code).queryFirst();

		//查询所有的子件
		List<TpProductBasisComponent> tpProductBasisComponent = new TpProductBasisComponent().setPcode(tpProductBasis.getCode()).setOrderby("A.Id DESC").queryList();

		Collections.sort(idList, Collections.reverseOrder());
		List<TpProductBasisComponent> tpProductBasisComponentNew;
		for (String id :idList){
			tpProductBasisComponentNew = tpProductBasisComponent.stream().filter(item -> item.getId() > Long.parseLong(id)).collect(Collectors.toList());
			if (tpProductBasisComponentNew.size() > 0){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return com.ys.vo.R.error("删除失败,子件信息删除必须按照顺序删除!");
			}
			TpProductBasisComponent oldMsg = new TpProductBasisComponent().setId(Long.parseLong(id)).queryFirst();
			//删除商品库子件
			tpProductBasisComponentMapper.deleteTrue(Long.parseLong(id));
			//删除Listing库子件
			diySqlMapper.delTpProductActiveComponentByCode(oldMsg.getCode());
		}
		return com.ys.vo.R.ok(EditDto.closeAndReload());
	}



	/**
	 * 参数验证
	 */
	@Override
	public String checkParams(List<Map<String, Object>> subData, Long menuId) throws Exception {
		String backMsg = "";
		if(subData==null || subData.size()<=0){
			return "参数为空！";
		}
		//获取pc字段数据
		List<YsCol> listField = new YsCol()
				.where("A.MenuId = "+menuId)
				//.setFormEditRequired(1)//编辑必填
				.setOrderby("A.SortNo ASC")
				.queryList();
		String decimalCount = "2";
		for (int i = 0; i < subData.size(); i++) {
			Map<String, Object> msg = subData.get(i);
			if(msg==null){
				backMsg = "第"+(i+1)+"行的参数为空！";
				continue;
			}
			//验证必填字段的非空；其他字段的长度限制、类型
			backMsg = checkUtil.checkTableColLengthAndDataType("TP_ProductBasicComponent",listField,msg,ysColItem->ysColItem.getFormEditRequired()!=null && ysColItem.getFormEditRequired() == 1);
			for(YsCol item:listField){
				if(item.getCode().equals("num") || item.getCode().equals("bprice")){
					if(msg.get(item.getCode())!=null && !checkUtil.isDecimal(msg.get(item.getCode()).toString(),decimalCount)){
						backMsg = item.getName()+"应为"+decimalCount+"位小数！";
					}
				}
			}
		}
		return backMsg;
	}



	/**
	 * 去除多余参数，只保留有权限编辑的参数
	 */
	@Override
	public List<Map<String, Object>> removeSurplusParams(JSONArray subData, Long menuId) throws Exception {
		List<Map<String, Object>> newSubData = new ArrayList<>();
		//获取pc编辑只读字段数据
		List<YsCol> listField = new YsCol()
				.where("A.MenuId = "+menuId)
				.queryList();

		for (int i = 0; i < subData.size(); i++) {
			JSONObject jSONObject = subData.getJSONObject(i);
			Map<String, Object> paramsNew = new HashMap<>();
			paramsNew.put("id",jSONObject.get("id"));//id必需
			paramsNew.put("pcode",jSONObject.get("pcode"));//母件编码必需
			if(listField!=null && listField.size()>0){
				for (String key : jSONObject.keySet()) {
					boolean isReadOnly = false;//是否只读
					for (YsCol item : listField) {
						if(item.getCode().equals(key) && item.getFormEditReadonly()!=null && item.getFormEditReadonly()==1){
							isReadOnly = true;
						}
					}
					if(!isReadOnly){//如果非只读，即是有权限修改的
						paramsNew.put(key,jSONObject.get(key));
					}
				}
			}
			newSubData.add(paramsNew);
		}

		return newSubData;
	}


}
